package leetcode.f1t100;

/**
 * 阿拉伯数字转换罗马数字
 * https://leetcode.com/problems/integer-to-roman/
 *
 * @author lichx
 * @date 2021/10/9 15:52
 */
public class Q12_IntegerToRoman {
    public String intToRoman(int num) {
        return f(num);
    }

    public static String f(int num) {
        if (num >= 4000) {
            return "";
        }
        int[] symbolInt = new int[]{1, 5, 10, 50, 100, 500, 1000};
        char[] symbol = new char[]{'I', 'V', 'X', 'L', 'C', 'D', 'M'};
        int l = symbol.length;
        int i = 2;
        StringBuilder s = new StringBuilder();
        while (num > 0 && i < l) {
            int a = num % symbolInt[i];
            int b = num % symbolInt[i - 1];
            // 9, 90, 900
            if (a == symbolInt[i] - symbolInt[i - 2]) {
                s.insert(0, symbol[i]);
                s.insert(0, symbol[i - 2]);
            } else if (b == symbolInt[i - 1] - symbolInt[i - 2]) {// 4, 40, 400
                s.insert(0, symbol[i - 1]);
                s.insert(0, symbol[i - 2]);
            } else {
                int c = b / symbolInt[i - 2];
                for (int j = 0; j < c; j++) {
                    s.insert(0, symbol[i - 2]);
                }
                if (a >= symbolInt[i - 1]) {
                    s.insert(0, symbol[i - 1]);
                }
            }
            num = num / symbolInt[i] * symbolInt[i];
            i += 2;
        }
        while (num > 0) {
            s.insert(0, symbol[l - 1]);
            num -= symbolInt[l - 1];
        }
        return s.toString();
    }

    public static void main(String[] args) {
        System.out.println(f(58));
    }
}
